﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using UnityEngine;
using Yeqian.ExtendLibrary;

namespace Assets.Scripts.Effect
{
    public class Timer : MonoBehaviour
    {
        public static Timer GetTimer(MonoBehaviour go)
        {
            Timer timer = go.gameObject.GetComponent<Timer>();
            if (!timer) timer = go.gameObject.AddComponent<Timer>();

            return timer;
        }

        /// <summary>
        /// 整数倒计时
        /// </summary>
        /// <param name="time">倒计时多长时间</param>
        /// <param name="onCountdown">每秒调用，范围 [0,time]</param>
        /// <param name="complete">倒计时结束的时候调用</param>
        public void Start2Countdown(int time, Action<int> onCountdown, Action complete = null)
        {
            StartCoroutine(CountdownCoroutine(time, onCountdown,complete));
        }
        private IEnumerator CountdownCoroutine(int time, Action<int> onCountdown,Action complete = null)
        {
            for (int i = time; i > 0; i--)
            {
                onCountdown?.InvokeForeach(i);
                yield return new WaitForSeconds(1);//等待1秒
            }
            onCountdown?.InvokeForeach(0);
            complete?.InvokeForeach();
        }

        /// <summary>
        /// 浮点数倒计时。与整数倒计时存在误差，每1s差1ms左右
        /// </summary>
        public void Start2Countdown(float time, Action<float> onCountdownFloat, Action complete = null)
        {
            StartCoroutine(CountdownCoroutine(time, onCountdownFloat,complete));
        }
        private IEnumerator CountdownCoroutine(float time, Action<float> onCountdownFloat, Action complete = null)
        {
            while (time > 0)
            {
                onCountdownFloat?.InvokeForeach(time);
                yield return null;//等待一帧
                time -= Time.deltaTime;
            }
            onCountdownFloat?.InvokeForeach(0);
            complete?.InvokeForeach();
        }

        public void Delay(float time, Action action)
        {
            StartCoroutine(DelayCoroutine(time, action));
        }
        private IEnumerator DelayCoroutine(float time, Action action)
        {
            yield return new WaitForSeconds(time);

            action?.InvokeForeach();
        }
    }
}
